﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMN.Models;
using CMN.Models.Interfaces;
using CMN.Entity;
using System.Web.Routing;
using CMN.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using CMN.Controllers.Filters;
namespace CMN.Controllers
{
    [ExceptionFilter]
    [LoggerFilter]
    [UserAuthorize]
    public class Normal_TagMapController : Controller
    {
        
        // 返回json字符串
        protected string returnJson = string.Empty;

        /// <summary>
        /// 转到View页面
        /// </summary>
        /// <returns></returns>
        public ViewResult Index()
        {
            return View("Index");//页面地址
        }

        public string SearchList(string actionId)
        {
            int pageSize = (int)Utils.GetQueryAndFormString("limit", this, 4, 1, DataType.Int);
            int pageIndex = (int)Utils.GetQueryAndFormString("start", this, 9, 1, DataType.Int);
            string sort = (string)Utils.GetQueryAndFormString("sort", this, 100, 0, DataType.Str);
            string search = (string)Utils.GetQueryAndFormString("s", this, 40, 0, DataType.Str);
            string path = (string)Utils.GetQueryAndFormString("path", this, 40, 0, DataType.Str);
            LuceneHelper lucene = new LuceneHelper();
            List<Module_ListInfo> list = new List<Module_ListInfo>();
            QueryParam qp = new QueryParam();
            qp.PageIndex = pageIndex / pageSize + 1;
            qp.PageSize = pageSize;
            qp.Where = search;
            if(!string.IsNullOrEmpty(search))
            list = lucene.Search(qp, path,200,1);
           
            returnJson = string.Concat("{totalPorperty:", qp.Count, ",root:", JsonConvert.SerializeObject(list), "}");
            return returnJson;
        }

        /// <summary>
        /// 返回标签列表列表
        /// </summary>
        /// <returns>json</returns>
        public string List(string actionId)
        {
            //返回json数组

            int pageSize = (int)Utils.GetQueryAndFormString("limit", this, 4, 1, DataType.Int);
            int pageIndex = (int)Utils.GetQueryAndFormString("start", this, 9, 1, DataType.Int);
            QueryParam qp = new QueryParam();
            qp.PageIndex = pageIndex / pageSize + 1; ;
            qp.PageSize = pageSize;
            if (!string.IsNullOrEmpty(actionId))
                qp.Where = string.Concat(" tagId=", actionId, " ");
            int recordNum = 0;
            IsoDateTimeConverter jsDataConvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
            jsDataConvert.DateTimeFormat = "yyyy-MM-dd";
            IDataService<Normal_TagMapEntity> Normal_TagMapSv = ServiceBuilder.BuildNormal_TagMapService();
            IDataService<Module_ArticleEntity> articleSv = ServiceBuilder.BuildModule_ArticleService();
            List<Normal_TagMapEntity> normal_tagmapList = Normal_TagMapSv.List(qp, out recordNum);
            string idList = string.Empty;
            foreach (Normal_TagMapEntity tag in normal_tagmapList)
            {
                idList = string.Concat(idList, tag.ModuleId, ",");
            }
            if (idList.Length > 1)
            {
                idList=idList.Substring(0,idList.Length-1);
            }
            qp = new QueryParam();
            qp.PageSize=pageSize;

            if(idList.Length>1)
            qp.Where=string.Concat(" id in (",idList,") ");
            int recordNum2 = 0;
            List<Module_ArticleEntity> articleList = articleSv.List(qp, out recordNum2);
            foreach (Module_ArticleEntity article in articleList)
            {
                foreach (Normal_TagMapEntity tag in normal_tagmapList)
                {
                    if (article.Id == tag.ModuleId)
                    {
                        tag.Title = article.Title;
                        break;
                    }
                }
            }
            returnJson = string.Concat("{totalPorperty:", recordNum, ",root:", JsonConvert.SerializeObject(normal_tagmapList, Formatting.Indented, jsDataConvert), "}");
            return returnJson;

        }

        /// <summary>
        /// 查看标签列表 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Look(string actionId)
        {
           IDataService<Normal_TagMapEntity> Normal_TagMapSv = ServiceBuilder.BuildNormal_TagMapService();
           int intId = Utils.StringToInt(actionId, 0);
            Normal_TagMapEntity normal_tagmap = Normal_TagMapSv.Look(intId);
            if (normal_tagmap != null)
                returnJson = string.Concat("{success:true,data:", JsonConvert.SerializeObject(normal_tagmap), "}");
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 更新标签列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Update(string actionId)
        {
            int intId = Utils.StringToInt(actionId, 0);
            if (intId != 0)
            {
                Normal_TagMapEntity normal_tagmap = new Normal_TagMapEntity();
                normal_tagmap.DataTable_Action = DataTableAction.Update;
                normal_tagmap.Id = intId;
                normal_tagmap.TagId = (Int32)Utils.GetQueryAndFormString("TagId", this, 10,  1 , DataType.Int);
                normal_tagmap.ModuleId = (Int32)Utils.GetQueryAndFormString("ModuleId", this, 10,  1 , DataType.Int);
                normal_tagmap.ModuleType = (String)Utils.GetQueryAndFormString("ModuleType", this, 1,  0, DataType.Str);
                IDataService<Normal_TagMapEntity> Normal_TagMapSv = ServiceBuilder.BuildNormal_TagMapService();
                if (Normal_TagMapSv.Update(normal_tagmap)== "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";
            }
            else
            {
                returnJson = "{success:'false'}";
            }
           
            return returnJson;
        }

        /// <summary>
        /// 新增标签列表
        /// </summary>
        /// <returns>json</returns>
        public string Insert(string actionId)
        {
            string articleIdList = (string)Utils.GetQueryAndFormString("moduleIdList",MethodType.Get, 300, 0, DataType.Str);
            Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            if (regex.IsMatch(articleIdList))
            {
                IDataService<Normal_TagsEntity> Normal_TagsSv = ServiceBuilder.BuildNormal_TagsService();

                IDataService<Module_ArticleEntity> articleSv = ServiceBuilder.BuildModule_ArticleService();
                string[] idList = articleIdList.Split('_');
                Normal_TagsEntity normal_tagmap = new Normal_TagsEntity();
                
                Int32 tagId = Utils.StringToInt(actionId, 0);
                normal_tagmap = Normal_TagsSv.Look(tagId);
                string[] articleTagList = null;
                
                for (int i = 0; i < idList.Length; i++)
                {
                    int articleId = Utils.StringToInt(idList[i], 0);

                    Module_ArticleEntity article = articleSv.Look(articleId);
                    articleTagList = article.Tags.Split(',');

                 
                    bool isHas = false;
                    //是否已经包括
                    for (int j = 0; j < articleTagList.Length; j++)
                    {
                        if (articleTagList[j] == actionId)
                        {
                            isHas = true;
                            break;
                        }

                    }
                    if (!isHas)
                    {
                        if (string.IsNullOrEmpty(article.Tags))
                        {
                            article.Tags =  tagId.ToString();
                        }
                        else
                            article.Tags = string.Concat(article.Tags, ",", tagId.ToString());
                        articleSv.Update(article);
                    }



                }
                returnJson = "{success:'true'}";


            }
            else
            {
                returnJson = "{success:'false',message:'参数类型不正确'}";
            }
            return returnJson;

        }

        /// <summary>
        /// 删除标签列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Delete(string actionId)
        {
            int intId = Utils.StringToInt(actionId, 0);
            if (intId != 0)
            {
                Normal_TagMapEntity normal_tagmap = new Normal_TagMapEntity();
                normal_tagmap.Id = intId;
                IDataService<Normal_TagMapEntity> Normal_TagMapSv = ServiceBuilder.BuildNormal_TagMapService();
                normal_tagmap=Normal_TagMapSv.Look(intId);
                IDataService<Module_ArticleEntity> articleSv = ServiceBuilder.BuildModule_ArticleService();
                Module_ArticleEntity article = articleSv.Look(normal_tagmap.ModuleId);
                string[] a = article.Tags.Split(',');
                if (a.Length < 1)
                {
                    if (Normal_TagMapSv.Delete(normal_tagmap) == "")
                    {
                        returnJson = "{success:'true'}";
                    }
                    else
                        returnJson = "{success:'false'}";
                }
                else
                {
                    string tagIdList = "";
                    for(int i = 0; i < a.Length; i++)
                    {
                        if (a[i] != normal_tagmap.TagId.ToString())
                        {
                            tagIdList = string.Concat(tagIdList, a[i], ",");
                        }
                       
                    }
                    if (tagIdList.Length > 1)
                    {
                        tagIdList = tagIdList.Substring(0, tagIdList.Length - 1);
                    }
                    article.Tags = tagIdList;
                    articleSv.Update(article);
                    returnJson = "{success:'true'}";
                }
            }
            else
            {
                returnJson = "{success:'false'}";
            }
            return returnJson;
        }

        

        /// <summary>
        /// 批量删除标签列表
        /// </summary>
        /// <param name="idList">id列表 234_4_5</param>
        /// <returns>json</returns>
        public string DeleteList(string actionId)
        {
            Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            if (regex.IsMatch(actionId))
            {
                IDataService<Normal_TagMapEntity> Normal_TagMapSv = ServiceBuilder.BuildNormal_TagMapService();
              
                IDataService<Module_ArticleEntity> articleSv = ServiceBuilder.BuildModule_ArticleService();
                string[] idList = actionId.Split('_');
                Normal_TagMapEntity normal_tagmap = new Normal_TagMapEntity();
                for (int i = 0; i < idList.Length; i++)
                {
                   

                    Int32 id = Utils.StringToInt(idList[i], 0);
                    normal_tagmap = Normal_TagMapSv.Look(id);
                  
                    Module_ArticleEntity article = articleSv.Look(normal_tagmap.ModuleId);
                    string[] a = article.Tags.Split(',');
                    if (a.Length < 1)
                    {
                        if (Normal_TagMapSv.Delete(normal_tagmap) == "")
                        {
                            returnJson = "{success:'true'}";
                        }
                        else
                            returnJson = "{success:'false'}";
                    }
                    else
                    {
                        string tagIdList = "";
                        for (int j = 0; j < a.Length; j++)
                        {
                            if (a[j] != normal_tagmap.TagId.ToString())
                            {
                                tagIdList = string.Concat(tagIdList, a[j], ",");
                            }

                        }
                        if (tagIdList.Length > 1)
                        {
                            tagIdList = tagIdList.Substring(0, tagIdList.Length - 1);
                        }
                        article.Tags = tagIdList;
                        articleSv.Update(article);
                       
                    }
                }
                returnJson = "{success:'true'}";
               

            }
            else
            {
                returnJson = "{success:'false',message:'参数类型不正确'}";
            }
            return returnJson;
        }

    }
}
